package orm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class PersonDbHelper {


	/**
	 * 
	 * @param context
	 * @param id
	 * @return null if no person with the given id is found
	 */
	public static Person getPersonByID(Context context, int id) {
		DBHelper mDbHelper = new DBHelper(context);
		SQLiteDatabase db = mDbHelper.getReadableDatabase();

		String selection = DBContract.Person.COLUMN_PERSON_ID + " = " + id;

		Cursor c = db.query(DBContract.Person.TABLE_NAME, 	// The table to query
				getAllProjectionCols(), 				// The columns to return
				selection, 									// The columns for the WHERE clause
				null, 										// The values for the WHERE clause
				null, 										// don't group the rows
				null, 										// don't filter by row groups
				null 										// The sort order
				);

		Person p = null;
		Date date = new Date();
		SimpleDateFormat iso8601Format = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		
		if (c.moveToFirst()) {
			try {
				date = iso8601Format.parse(c.getString(3));
			} catch (java.text.ParseException e) {
				date = new Date();
				//e.printStackTrace();
			}
			p = new Person(
					Integer.parseInt(c.getString(0)), 
					c.getString(1),
					c.getString(2), 
					c.getString(3), 
					c.getString(4), 
					c.getString(5), 
					date, 
					c.getString(7));
		}
		
		mDbHelper.close();
		if (c != null && ! c.isClosed()) {
			c.close();
		}
		if (db != null) {
			db.close();
		}
		
		if(p != null){
			return p;
		}
		
		return null;
	}
	
	/**
	 * Deletes the given Person ID
	 * @param context
	 * @param id
	 * the number of rows affected if a whereClause is passed in, 0 otherwise. 
	 */
	public static int delete(Context context, int id){
		DBHelper mDbHelper = new DBHelper(context);
		SQLiteDatabase db = mDbHelper.getReadableDatabase();
		
		String selection = DBContract.Person.COLUMN_ANDROID_ID + " = '" + id + "'";
		String whereArgs[] = null;
		int i =  db.delete(DBContract.Person.TABLE_NAME, selection, whereArgs);
		mDbHelper.close();
		return i;
	}

	/**
	 * Use this function if it is not sure if the given person already exists
	 * @param context
	 * @param person
	 * @return ID if new Person is added, or updated. -1 or 0 if no success
	 */
	public static long savePerson(Context context, Person person) {
		
		if(person.getID() != -1 && getPersonByID(context, person.getID()) != null){
			updatePerson(context, person);
			return person.getID();
		} else {
			return addPerson(context, person);
		}

	}
	
	/**
	 * 
	 * @param context
	 * @param person
	 * @return the row ID of the newly inserted row, or -1 if an error occurred
	 */
	public static long addPerson(Context context, Person person) {
		
		DBHelper mDbHelper = new DBHelper(context);
		SQLiteDatabase db = mDbHelper.getWritableDatabase();

		long id = db.insert(DBContract.Person.TABLE_NAME,
				DBContract.Person.COLUMN_NULLABLE, getAllValues(person));
		mDbHelper.close();
		return id;


	}

	/**
	 * 
	 * @param context
	 * @param person
	 * @return the number of rows affected
	 * if = no update
	 */
	public static long updatePerson(Context context, Person person) {
		
		DBHelper mDbHelper = new DBHelper(context);
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		
		long id = db.update(DBContract.Person.TABLE_NAME, getAllValues(person), DBContract.Person.COLUMN_PERSON_ID + " = " + person.getID(), null);
		mDbHelper.close();
		return id;
	}

	/**
	 * 
	 * @param context
	 * @param android_id
	 * @return null if no person with the given android_id exists
	 */
	public static Person getPersonByAndroi_ID(Context context, String android_id) {
		
		DBHelper mDbHelper = new DBHelper(context);
		SQLiteDatabase db = mDbHelper.getReadableDatabase();

		String selection = DBContract.Person.COLUMN_ANDROID_ID + " = '" + android_id + "'";

		Cursor c = db.query(DBContract.Person.TABLE_NAME, 	// The table to query
				getAllProjectionCols(), 				// The columns to return
				selection, 									// The columns for the WHERE clause
				null, 										// The values for the WHERE clause
				null, 										// don't group the rows
				null, 										// don't filter by row groups
				null 										// The sort order
				);

		Person p = null;
		Date date = new Date();

		if (c.moveToFirst()) {
			p = new Person(
					Integer.parseInt(c.getString(0)), 
					c.getString(1),
					c.getString(2), 
					c.getString(3), 
					c.getString(4), 
					c.getString(5), 
					new Date(), 
					c.getString(7));
		}
		
		mDbHelper.close();
		if (c != null && ! c.isClosed()) {
			c.close();
		}
		if (db != null) {
			db.close();
		}
		
		return p;

	}
	
	/**
	 * ContentValues: This class is used to store a set of values that the ContentResolver can process.
	 * @param person
	 * @return a map of all values/columns, where column names are the keys
	 */
	private static ContentValues getAllValues(Person person){
		
		ContentValues values = new ContentValues();
		values.put(DBContract.Person.COLUMN_TITLE, person.getTitle());
		values.put(DBContract.Person.COLUMN_FNAME, person.getFName());
		values.put(DBContract.Person.COLUMN_LNAME, person.getLName());
		values.put(DBContract.Person.COLUMN_NATION, person.getNation());
		values.put(DBContract.Person.COLUMN_GENDER, person.getGender());
		values.put(DBContract.Person.COLUMN_DATE_OF_BIRTH, person.getDateOfBirth().toString());
		values.put(DBContract.Person.COLUMN_ANDROID_ID, person.getAndroidID());
		
		return values;
	}
	
	/**
	 * Define a projection that specifies which columns from the database
	 * you will actually use after this query.
	 * @return
	 */
	private static String[] getAllProjectionCols(){
		
		String[] projection = { DBContract.Person.COLUMN_PERSON_ID,
				DBContract.Person.COLUMN_TITLE,
				DBContract.Person.COLUMN_FNAME, 
				DBContract.Person.COLUMN_LNAME,
				DBContract.Person.COLUMN_NATION,
				DBContract.Person.COLUMN_GENDER, 
				DBContract.Person.COLUMN_DATE_OF_BIRTH,
				DBContract.Person.COLUMN_ANDROID_ID };
		
		return projection;
	}

	public static void getFitnessData(int _id) {
		// TODO Auto-generated method stub
		
	}

	public static ArrayList<Person> getAllPerson(Context context) {
		ArrayList<Person> personList = new ArrayList<Person>();
		
		DBHelper mDbHelper = new DBHelper(context);
		SQLiteDatabase db = mDbHelper.getReadableDatabase();

		Cursor c = db.query(DBContract.Person.TABLE_NAME, 	// The table to query
				getAllProjectionCols(), 				// The columns to return
				null, 									// The columns for the WHERE clause
				null, 										// The values for the WHERE clause
				null, 										// don't group the rows
				null, 										// don't filter by row groups
				null 										// The sort order
				);

		Date date = new Date();
		SimpleDateFormat iso8601Format = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		
		if (c.moveToFirst()) {
				try {
					date = iso8601Format.parse(c.getString(3));
				} catch (java.text.ParseException e) {
					date = new Date();
					e.printStackTrace();
				}
		    do {
				personList.add(new Person(
						Integer.parseInt(c.getString(0)), 
						c.getString(1),
						c.getString(2), 
						c.getString(3), 
						c.getString(4), 
						c.getString(5), 
						date, 
						c.getString(7)));

		     } while (c.moveToNext());
		}
		mDbHelper.close();
		if (c != null && ! c.isClosed()) {
			c.close();
		}
		if (db != null) {
			db.close();
		}
		return personList;
	}
	
	/*
	 * Creates a empty user with the current Android ID
	 */
	public static Person addDummyUser(Context context, String adroid_id) {

		long id = addPerson(context, new Person(-1, "Herrn", "Martin", "Lang", "Italien", "m", new Date(),
				adroid_id));
		return PersonDbHelper.getPersonByID(context, (int) id);

	}

}